import logging
from typing import Optional

import jwt
from fastapi import Depends, Header, HTTPException, Request

from app.core.ctx import CTX_USER_ID
from app.models import Role, User
from app.settings import settings


log = logging.getLogger(__name__)


class AuthControl:
    @classmethod
    async def is_authed(cls,
                        token: str = Header(None, description="token验证"),
                        authorization: str = Header(None, description="Authorization验证")) -> Optional["User"]:
        try:
            token = token or authorization

            # 如果是Bearer token格式，需要去掉"Bearer "前缀
            if token and token.startswith("Bearer "):
                token = token[7:]

            if token == "dev":
                user = await User.filter().first()
                user_id = user.id
            else:
                decode_data = jwt.decode(token, settings.SECRET_KEY, algorithms=settings.JWT_ALGORITHM)
                user_id = decode_data.get("user_id")
            user = await User.filter(id=user_id).first()
            if not user:
                raise HTTPException(status_code=401, detail="Authentication failed")
            CTX_USER_ID.set(int(user_id))
            return user
        except jwt.DecodeError:
            raise HTTPException(status_code=401, detail="无效的Token")
        except jwt.ExpiredSignatureError:
            raise HTTPException(status_code=401, detail="登录已过期")
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"{repr(e)}")


class PermissionControl:

    @classmethod
    async def has_permission(cls, request: Request,
        current_user: User = Depends(AuthControl.is_authed)) -> None:
        """
        验证接口权限
        """
        if current_user.is_superuser:
            return
        method = request.method
        path = request.url.path
        roles: list[Role] = await current_user.roles
        if not roles:
            raise HTTPException(status_code=403, detail="The user is not bound to a role")
        apis = [await role.apis for role in roles]
        permission_apis = list(set((api.method, api.path) for api in sum(apis, [])))
        if (method, path) not in permission_apis:
            raise HTTPException(status_code=403,
                                detail=f"Permission denied method:{method} path:{path}")

    @classmethod
    async def has_permission2(cls, request: Request,
        current_user: User = Depends(AuthControl.is_authed)):
        """
        暂不验证接口权限
        :param current_user: 登录用户
        :param request: 请示对象
        """
        path = request.url.path
        log.info("用户[%s],请求接口[%s],", current_user.username, path)
        return


DependAuth = Depends(AuthControl.is_authed)
DependPermission = Depends(PermissionControl.has_permission2)
